import { Icon } from '@amcax/base';
import { CircleBar } from '@app-base/common/widgets/CircleBar';
import { circleBarButtons } from '@app-base/common/widgets/CircleBar/config';
import { CircleBarTableButtonItem } from '@app-base/common/widgets/CircleBar/types';
import { useUserSettingCustomer } from '@app-base/common/providers/userSettingProvider';
import { httpSettingApi } from '@app-base/server/setting-http';
import { i18n } from '@app-nextmesh/common/utils';
import { Checkbox, Input, Select } from 'antd';
import { debounce } from 'lodash';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { SettingsPanel } from '../SettingsPanel';
import { DEFAULT_MOUSE_GESTURE } from '@app-base/common/providers/const';
import { MessageTip } from '@app-base/common/utils/MessageTip';
import {
  getAllButtons,
  getFilteredButtonList,
} from '../../utils/filterHelpers';

const ENVIRONMENT_OPTIONS = [
  { value: 'part_env', label: 'settings.part_env' },
  { value: 'sketch_env', label: 'settings.sketch_env' },
  { value: 'product_env', label: 'settings.product_env' },
];

const MOUSE_COUNT_OPTIONS = [
  { value: 2, label: '2个笔势' },
  { value: 3, label: '3个笔势' },
  { value: 4, label: '4个笔势' },
  { value: 8, label: '8个笔势' },
  { value: 12, label: '12个笔势' },
];

interface MouseGesturesProps {
  onCloseDialog?: () => void;
}

const MouseGestures: React.FC<MouseGesturesProps> = ({ onCloseDialog }) => {
  const { mouseGestureConfig, setMouseGestureConfig, currentEnvironment } =
    useUserSettingCustomer();
  const [searchText, setSearchText] = useState('');
  const [mouseCount, setMouseCount] = useState(8);
  const [environment, setEnvironment] = useState(currentEnvironment);
  const [draggingItem, setDraggingItem] = useState<string | null>(null);

  const [enableMouseGesture, setEnableMouseGesture] = useState(
    mouseGestureConfig?.enableMouseGesture ?? false,
  );

  const [buttons, setButtons] = useState<string[]>(
    mouseGestureConfig?.[environment] ?? DEFAULT_MOUSE_GESTURE[environment],
  );

  const debouncedSetSearch = useCallback(
    debounce((value: string) => {
      setSearchText(value);
    }, 300),
    [],
  );

  useEffect(() => {
    if (mouseGestureConfig?.[environment]) {
      setButtons(mouseGestureConfig[environment]);
      setMouseCount(mouseGestureConfig[environment].length);
    }
  }, [environment, mouseGestureConfig]);

  const resetToDefault = useCallback(() => {
    setEnableMouseGesture(DEFAULT_MOUSE_GESTURE.enableMouseGesture);
    setButtons(DEFAULT_MOUSE_GESTURE[environment]);
    setMouseCount(DEFAULT_MOUSE_GESTURE[environment].length);

    MessageTip.info('已恢复默认设置，保存后生效');
  }, [environment]);

  const handleSearch = useCallback(
    (value: string) => {
      debouncedSetSearch(value);
    },
    [debouncedSetSearch],
  );

  const handleDrop = useCallback(
    (label: string, idx: number) => {
      if (draggingItem) {
        const newButtons = [...buttons];
        newButtons[idx] = draggingItem;
        setButtons(newButtons);
      }
    },
    [buttons, draggingItem],
  );

  const handleDragStart = useCallback((name: string) => {
    setDraggingItem(name);
  }, []);

  const handleDragEnd = useCallback(() => {
    setDraggingItem(null);
  }, []);

  const handleEnableChange = useCallback(
    (checked: boolean) => {
      setEnableMouseGesture(checked);
      setMouseGestureConfig({
        ...mouseGestureConfig,
        enableMouseGesture: checked,
      });
    },
    [mouseGestureConfig, setMouseGestureConfig],
  );

  const handleMouseCountChange = useCallback(
    (value: number) => {
      setMouseCount(value);
      const currentButtons = DEFAULT_MOUSE_GESTURE[environment].slice(0, value);
      const remainingSlots = Math.max(0, value - currentButtons.length);
      setButtons(currentButtons.concat(Array(remainingSlots).fill('')));
    },
    [environment],
  );

  const allButtons = useMemo(() => getAllButtons(), []);

  const filteredButtonList = useMemo(() => {
    return getFilteredButtonList(allButtons, environment, searchText);
  }, [allButtons, environment, searchText]);

  const handleSave = useCallback(async () => {
    try {
      const newConfig = {
        ...mouseGestureConfig,
        [environment]: buttons,
        enableMouseGesture,
      };

      const apiParams = {
        partEnv: newConfig.part_env || [],
        sketchEnv: newConfig.sketch_env || [],
        productEnv: newConfig.product_env || [],
        enableMouseGesture: newConfig.enableMouseGesture,
      };

      await httpSettingApi.saveUserMouseGestureDetail(apiParams);
      MessageTip.success('保存成功');

      setMouseGestureConfig(newConfig);
    } catch (error) {
      console.error('保存鼠标手势配置失败:', error);
      MessageTip.error('保存失败');
    }
  }, [
    environment,
    buttons,
    enableMouseGesture,
    mouseGestureConfig,
    setMouseGestureConfig,
  ]);

  const renderCommandItem = useCallback(
    (button: CircleBarTableButtonItem) => (
      <tr
        key={`${environment}-${button.name}`}
        draggable
        className={`h-[30px] cursor-grab border-b border-zinc-100 ${
          draggingItem === button.label ? 'bg-zinc-100' : ''
        }`}
        onDragStart={() => handleDragStart(button.name)}
        onDragEnd={handleDragEnd}
      >
        <td className='align-top p-2'>{i18n.t(button.type)}</td>
        <td className='align-top p-2'>
          <Icon
            name={button.icon}
            size={16}
            className='mr-1 inline-block'
          />
          {i18n.t(button.label)}
        </td>
      </tr>
    ),
    [environment, draggingItem, handleDragStart, handleDragEnd],
  );

  return (
    <SettingsPanel
      onRestoreDefaults={resetToDefault}
      onSave={handleSave}
      onCancel={onCloseDialog}
    >
      <div className='flex w-[560px] gap-10 m-2.5'>
        <div className='flex-1'>
          <div className='flex items-center h-8 mb-2.5'>
            <span className='mr-2 whitespace-nowrap'>
              {i18n.t('settings.environment')}：
            </span>
            <Select
              placeholder={i18n.t('settings.environment')}
              className='flex-1'
              value={environment}
              options={ENVIRONMENT_OPTIONS.map((option) => ({
                ...option,
                label: i18n.t(option.label),
              }))}
              onChange={setEnvironment}
            />
          </div>

          <div className='flex items-center h-8 mb-2.5'>
            <span className='mr-2 whitespace-nowrap'>
              {i18n.t('settings.search')}：
            </span>
            <Input
              placeholder={i18n.t('settings.search')}
              className='flex-1'
              onChange={(e) => handleSearch(e.target.value)}
            />
          </div>

          <div className='h-[360px] overflow-auto border border-zinc-200 rounded-md'>
            <table className='w-full select-none border-collapse'>
              <thead>
                <tr>
                  <th className='sticky top-0 z-10 border-b border-zinc-200 bg-white p-2 text-left font-bold'>
                    {i18n.t('settings.type')}
                  </th>
                  <th className='sticky top-0 z-10 border-b border-zinc-200 bg-white p-2 text-left font-bold'>
                    {i18n.t('settings.command')}
                  </th>
                </tr>
              </thead>
              <tbody>{filteredButtonList.map(renderCommandItem)}</tbody>
            </table>
          </div>
        </div>

        <div className='flex-1'>
          <Checkbox
            className='mb-2.5 h-[30px]'
            checked={enableMouseGesture}
            onChange={(e) => handleEnableChange(e.target.checked)}
          >
            {i18n.t('settings.enableMouseGesture')}
          </Checkbox>

          <div className='flex items-center h-8 mb-2.5'>
            <Select
              className='flex-1'
              value={mouseCount}
              options={MOUSE_COUNT_OPTIONS}
              onChange={handleMouseCountChange}
            />
          </div>

          <div className='h-8 mb-2.5 text-center'>
            {i18n.t('settings.mouseGestureGuide')}
          </div>
          <div className='w-full mb-2.5'>
            <CircleBar
              isEdit={true}
              onDrop={handleDrop}
              buttons={circleBarButtons(environment, buttons)}
              environment={environment}
            />
          </div>
          <div className='h-8 mt-[30px] text-right'>
            *{i18n.t('settings.dragToMouseGestureGuide')}
          </div>
        </div>
      </div>
    </SettingsPanel>
  );
};

export default React.memo(MouseGestures);
